package com.lz.myblog.controller;

import com.lz.myblog.entity.Category;
import com.lz.myblog.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller //注解为请求控制处理
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryRepository categoryRepository;//注入对象

    @RequestMapping("/add")  //跳转到添加页面
    public String add(){


        return "admin/categoryAdd";
    }

    @RequestMapping("/save")
    public String save(Category category){
        categoryRepository.save(category);
        return "redirect:list";
    }

    @RequestMapping("/edit")
    public String edit(int cid, Model model){
        Category one = categoryRepository.getOne(cid);
        model.addAttribute("one",one);
        return "admin/categoryUpdate";
    }
    @RequestMapping("/update")
    public String update(Category category){
        categoryRepository.save(category);
        return "redirect:list";
    }

    @RequestMapping("/detail")
    public String detail(int cid, Model model){
        Category one = categoryRepository.getOne(cid);
        model.addAttribute("one",one);
        return "admin/categoryDetail";
    }

    @RequestMapping("/delete")
    public String delete(int cid){
        categoryRepository.deleteById(cid);
        return "redirect:list";
    }

    @RequestMapping("/list")//localhost:8848/userinfo/list
    public String list(Model model, Integer p){
        int pageSize = 10; //每页显示10条数据
        p = p==null?1:p; //判断是否传递了页码
//        p= p-1;
        Sort sort = Sort.by(Sort.Direction.DESC,"categoryid");  //排序条件
        Page<Category> all = categoryRepository.findAll(PageRequest.of(p - 1, pageSize,sort));
        List<Category> content = all.getContent();
        int totalPages = all.getTotalPages();
        //绑定参数
        model.addAttribute("content",content);
        model.addAttribute("totalPages",totalPages);
        model.addAttribute("currenPage",p);
        return "admin/categoryList";//跳转到jsp页面
    }
}
